<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Kame
 * Date: 23/03/13
 * Time: 09:42 PM
 */
namespace Site\Model;

use Zend\Db\TableGateway\TableGateway;

class UserTable
{
    protected $tableGateway;

    public function __construct(TableGateway $gateway)
    {
        $this->tableGateway = $gateway;
    }

    public function fetchAll()
    {
        return $this->tableGateway->select();
    }

    /**
     * @param $usuario
     * @return \Site\Model\User
     */
    public function getUserByID($usuario)
    {
        $usuario = (int)$usuario;
        $row = $this->tableGateway->select(array('usuario' => $usuario))->current();
        return $row;
    }

    public function getUserByNick($nick)
    {
        $row = $this->tableGateway->select(array('nick' => $nick))->current();
        return $row;
    }

    public function getUserByNickPase($usuario, $pase)
    {
        $usuario = (int)$usuario;
        return $this->tableGateway->select(array(
            'usuario' => $usuario,
            'pase' => $pase
        ));
    }

    public function saveUser(User $user)
    {
        $data = array(
            'pase' => $user->pase,
            'nick' => $user->nick,
            'nombre' => $user->nombre,
            'apellido' => $user->apellido,
            'correo' => $user->correo,
            'sitioweb' => $user->sitioweb,
            'avatar' => $user->avatar,
            'facebook_token' => $user->facebook_token,
        );
        $usuario = (int)$user->usuario;
        if ($usuario == 0) {
            $this->tableGateway->insert($data);
            return true;
        } else {
            if($this->getUserByID($usuario)){
                $this->tableGateway->update($data,array('usuario' => $usuario));
                return true;
            }
        }
        return false;
    }

    public function deleteUser($usuario){
        $this->tableGateway->delete(array('usuario' => $usuario));
    }
}
